/*
 * StartApplication.java
 *
 * Created on Jul 21, 2009 4:48:43 PM;
 */

package org.sunspotworld;

import com.sun.spot.core.resources.Resources;
import com.sun.spot.core.resources.transducers.ILightSensor;
import com.sun.spot.core.resources.transducers.ISwitch;
import com.sun.spot.core.resources.transducers.ITriColorLED;
import com.sun.spot.core.util.Utils;
import com.sun.spot.edemo.EDemoBoard;
import com.sun.spot.espot.service.BootloaderListenerService;
import com.sun.spot.ieee_802_15_4_radio.IRadioPolicyManager;
import com.sun.spot.ieee_802_15_4_radio.util.IEEEAddress;
import com.sun.spot.multihop.io.j2me.radiogram.Radiogram;
import com.sun.spot.multihop.io.j2me.radiogram.RadiogramConnection;
import java.io.IOException;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * The startApp method of this class is called by the VM to start the
 * application.
 * 
 * The manifest specifies this class as MIDlet-1, which means it will
 * be selected for execution.
 */
public class StartApplication extends MIDlet {

    private ITriColorLED [] leds = EDemoBoard.getInstance().getLEDs();
    private ILightSensor light = EDemoBoard.getInstance().getLightSensor();
    private static final long SECONDS = 1000;
    private static final long PAUSE = 4*SECONDS;

    protected void startApp() throws MIDletStateChangeException {
        System.out.println("Hello, world");
        BootloaderListenerService.getInstance().start();   // monitor the USB (if connected) and recognize commands from host

        long ourAddr = ((IRadioPolicyManager) Resources.lookup(IRadioPolicyManager.class)).getIEEEAddress();
        System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));

        ISwitch sw1 = EDemoBoard.getInstance().getSwitches()[EDemoBoard.SW1];
        leds[0].setRGB(100,0,0);                // set color to moderate red
        RadiogramConnection conn=null;
        Radiogram rg;
        while (sw1.isOpen()) {
            try {
                conn = (RadiogramConnection) Connector.open("radiogram://broadcast:87");
                rg = (Radiogram)conn.newDatagram(conn.getMaximumLength());
                while (sw1.isOpen()) {                  // done when switch is pressed
                    rg.reset();
                    rg.writeLong(System.currentTimeMillis());
                    rg.writeInt(light.getAverageValue());
                    conn.send(rg);
                    leds[0].setOn();                    // Blink LED
                    Utils.sleep(PAUSE / 2);                  // wait 1 second
                    leds[0].setOff();
                    Utils.sleep(PAUSE / 2);
                }
            } catch (IOException iOException) {
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        }
        notifyDestroyed();                      // cause the MIDlet to exit
    }

    protected void pauseApp() {
        // This is not currently called by the Squawk VM
    }

    /**
     * Called if the MIDlet is terminated by the system.
     * I.e. if startApp throws any exception other than MIDletStateChangeException,
     * if the isolate running the MIDlet is killed with Isolate.exit(), or
     * if VM.stopVM() is called.
     * 
     * It is not called if MIDlet.notifyDestroyed() was called.
     *
     * @param unconditional If true when this method is called, the MIDlet must
     *    cleanup and release all resources. If false the MIDlet may throw
     *    MIDletStateChangeException  to indicate it does not want to be destroyed
     *    at this time.
     */
    protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
        for (int i = 0; i < 8; i++) {
            leds[i].setOff();
        }
    }


}
